﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aier.dataaccess.dapper
{
    public class DapperHelper
    {
        protected string sqlConnectionStrDefault = null;

        public DapperHelper(string sqlConnectionStr)
        {
            this.sqlConnectionStrDefault = sqlConnectionStr;
        }

        public DapperHelper()
        {
            this.sqlConnectionStrDefault = System.Configuration.ConfigurationManager.ConnectionStrings["Aier_CRMDB"].ConnectionString;
        }



        public void UseSqlConnect(Action<SqlConnection> action)
        {
            using (SqlConnection sqlConn = new SqlConnection(sqlConnectionStrDefault))
            {
                sqlConn.Open();
                action(sqlConn);
            }
        }

        public T UseSqlConnect<T>(Func<SqlConnection, T> func)
        {
            using (SqlConnection sqlConn = new SqlConnection(sqlConnectionStrDefault))
            {
                sqlConn.Open();
                return func(sqlConn);
            }
        }

        public T ExecueWithoutTransaction<T>(Func<SqlConnection,T> func)
        {
            return UseSqlConnect(func);
        }

        public void ExecueWithoutTransaction(Action<SqlConnection> action)
        {
            UseSqlConnect(action);
        }

        public bool ExecueWithTransaction(Func<SqlConnection, IDbTransaction, int> func)
        {
            int count = 0;
            UseSqlConnect(conn =>
            {
                IDbTransaction transaction = conn.BeginTransaction();
                try
                {
                    count = func(conn, transaction);
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw ex;
                }
                finally
                {
                    if (transaction != null)
                        transaction.Dispose();
                }
            });

            return count > 0;
        }
    }
}
